package com.shortlink.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.shortlink.common.base.errcode.AuthErrorCode;
import com.shortlink.auth.config.AuthProperties;
import com.shortlink.auth.dto.req.UserLoginReqDTO;
import com.shortlink.auth.dto.resp.UserLoginRespDTO;
import com.shortlink.auth.remote.UserRemoteService;
import com.shortlink.auth.service.AuthService;
import com.shortlink.auth.util.JwtUtils;
import com.shortlink.common.base.Result;
import com.shortlink.common.exception.ClientException;
import com.shortlink.common.exception.RemoteException;
import com.shortlink.common.user.UserContext;
import com.shortlink.common.user.UserInfoDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 认证服务接口实现
 *
 * @author wp
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    private final JwtUtils jwtUtils;
    private final AuthProperties authProperties;
    private final UserRemoteService userRemoteService;

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        String username = userLoginReqDTO.getUsername();
        String password = userLoginReqDTO.getPassword();
        if (!ObjectUtil.isAllNotEmpty(username, password)) {
            log.error(String.format("username(%s) password(%s) 不能为空", username, password));
            throw new ClientException("参数错误");
            //throw new ClientException(AuthErrorCode.NULL_USERNAME_PASSWORD);
        }

        Result<UserInfoDTO> result = userRemoteService.login(username, password);

        UserInfoDTO userInfoDTO = result.getData();
        if (ObjectUtil.isEmpty(userInfoDTO)) {
            throw new ClientException(AuthErrorCode.INCORRECT_USERNAME_PASSWORD);
        }

        String token = jwtUtils.generateToken(userInfoDTO);
        return new UserLoginRespDTO(token);
    }

    @Override
    public UserInfoDTO auth(String token, String requestPath) {
        if (!ObjectUtil.isAllNotEmpty(requestPath)) {
            log.error(String.format("requestPath(%s) 不能为空", requestPath));
            throw new ClientException("参数错误");
        }

        if (authProperties.isRequireInter(requestPath)) {
            log.error(String.format("token(%s) requestPath(%s) 内部接口无权限", token, requestPath));
            throw new ClientException(AuthErrorCode.NO_AUTH);
        }

        UserInfoDTO userInfoDTO = UserContext.getUser();
        if (authProperties.isRequireLogin(requestPath) && ObjectUtil.isEmpty(userInfoDTO)) {
            log.error(String.format("token(%s) requestPath(%s) userInfo(%s) 需要登录", token, requestPath, userInfoDTO));
            throw new ClientException(AuthErrorCode.NO_AUTH);
        }
        return userInfoDTO;
    }
}
